<template>
  <div class="page-container">
    <!-- 顶部标题 -->
    <div class="header-title">
      <h1>成都市市场监督管理局教育培训中心</h1>
    </div>
    <div class="login">
      <div class="login-card">
        <!-- Tab切换 -->
        <div class="login-tabs">
          <div
            :class="['tab-item', { active: activeTab === 'phone' }]"
            @click="activeTab = 'phone'"
          >
            考试登录
          </div>
        </div>

        <el-form ref="loginForm1" :model="loginForm1" :rules="loginRules1" class="login-form" v-if="activeTab === 'phone'">
          <!-- 手机号登录表单 -->
          <div>
            <el-form-item prop="phonenumber" label="手机号">
              <el-input
                v-model="loginForm1.phonenumber"
                auto-complete="off"
                placeholder="请输入手机号"
                maxlength="11"
              />
            </el-form-item>
            <el-form-item prop="code"  label="验证码">
              <el-input
                v-model="loginForm1.code"
                auto-complete="off"
                placeholder="请输入验证码"
                style="width: 60%"
                maxlength="6"
              />
              <div class="register-code">
                <el-button
                  @click="send"
                  :disabled="exTime !== 60 || !isPhoneValid"
                  :loading="sendingCode"
                >
                  {{exText}}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item prop="name" label="姓名">
              <el-input
                v-model="loginForm1.name"
                auto-complete="off"
                placeholder="请输入姓名"
              />
            </el-form-item>
            <el-form-item prop="idNumber" label="身份证号">
              <el-input
                v-model="loginForm1.idNumber"
                auto-complete="off"
                placeholder="身份证号"
              />
            </el-form-item>
          </div>

          <!-- 协议同意区域 -->
          <div class="protocol">
            <span
              :class="['protocol-checkbox', { active: loginForm1.agreed }]"
              @click="loginForm1.agreed = !loginForm1.agreed"
            ></span>
            <span class="protocol-text">已阅并同意</span>
            <a target="_blank" class="protocol-link" href="隐私协议链接">《隐私协议》</a>
            <p v-show="showProtocolError1" class="error-msg">
              <span class="msg-icon"></span>请先勾选协议
            </p>
          </div>
          <!-- 按钮组 -->
          <el-form-item class="custom-button-group">
            <div class="button-container">
              <div class="button-wrapper">
                <el-button
                  :loading="loading"
                  size="medium"
                  type="primary"
                  class="action-button"
                  @click.native.prevent="handleLogin"
                >
                  <span v-if="!loading">登 录</span>
                  <span v-else>登 录 中...</span>
                </el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 底部 -->
      <div class="el-login-footer">
        <span></span>
      </div>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getPhoneCode, phoneRegister, sendCode, examLogin} from "@/api/login";

export default {
  name: "Login",
  data() {
    // 账号密码验证规则
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };

    return {
      phoneFlag:true,
      title: process.env.VUE_APP_TITLE,
      activeTab: 'phone', // 当前激活的标签页
      codeUrl: "",
      loginForm1: {
        phonenumber: "",
        code: "",
        agreed: false,
        uuid: "",
        name :"",
        idNumber:"",
      },
      loginRules1: {
        phonenumber: [
          { required: true, trigger: "blur", message: "请输入手机号" },
          { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        code: [
          { required: true, trigger: "blur", message: "请输入验证码" },
          { pattern: /^\d{6}$/, message: "验证码为6位数字", trigger: "blur" }
        ],
        name : [
          { required: true, trigger: "blur", message: "请输入姓名" },
        ],
        IdNumber: [
          { required: true, trigger: "blur", message: "请输入身份证号" },
        ],
      },
      loading: false,
      sendingCode: false,
      captchaEnabled: true,
      exText: '获取验证码',
      exTime: 60,
      timerId: null,
      redirect: undefined,
      showProtocolError1: false,
      showProtocolError2: false,
      uuid: '', // 存储UUID
    }
  },
  computed: {
    isPhoneValid() {
      return /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(this.loginForm1.phonenumber)
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    },
    exTime(val) {
      if (val <= 0) {
        clearInterval(this.timerId)
        this.exText = "获取验证码"
        this.exTime = 60
      } else if (val < 60) {
        this.exText = `${val}秒后重试`
      }
    },
    'loginForm1.agreed'() {
      // 当用户勾选协议时隐藏错误提示
      if (this.loginForm1.agreed) {
        this.showProtocolError1 = false
      }
    },
    activeTab(val) {
      this.switchLoginType(val)
    }
  },
  created() {
    this.getCode();
    this.getCookie()
  },
  methods: {
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm2 = {
        username: username === undefined ? this.loginForm2.username : username,
        password: password === undefined ? this.loginForm2.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    // 生成UUID
    generateUuid() {
      this.uuid =  'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
      console.log('生成的UUID:', this.uuid)
    },

    getCode() {
        getCodeImg().then(res => {
          this.codeUrl = `data:image/gif;base64,${res.img}`;
          this.loginForm2.uuid = res.uuid
        });
    },

    send() {
      if (!this.isPhoneValid) {
        this.$message.error("请输入正确的手机号码！")
        return
      }
      this.sendingCode = true
      this.generateUuid();
      sendCode(this.loginForm1.phonenumber, this.uuid)
        .then(res => {
          if (res.code === 200) {
            this.$message.success("短信发送成功！")
            this.startCountdown()
          } else {
            this.$message.error(res.msg || "短信发送失败")
            this.exTime = 60 // 重置倒计时
          }
        })
        .catch(error => {
          this.$message.error("短信发送失败")
          console.error("发送验证码失败:", error)
          this.exTime = 60 // 重置倒计时
        })
        .finally(() => {
          this.sendingCode = false
        })
    },

    startCountdown() {
      this.exTime = 59
      this.timerId = setInterval(() => {
        this.exTime--
      }, 1000)
    },

    handleLogin() {
        // 验证协议是否勾选
        if (!this.loginForm1.agreed) {
          this.showProtocolError1 = true
          this.$message.error("请先同意隐私协议")
          return
        }
          this.$refs.loginForm1.validate(valid => {
            if (valid) {
              this.loading = true
              this.showProtocolError1 = false

              let loginData = {};
                loginData = {
                  phone: this.loginForm1.phonenumber,
                  code: this.loginForm1.code,
                  uuid:this.uuid,
                  name:this.loginForm1.name,
                  idNumber:this.loginForm1.idNumber
                };
                this.$store.dispatch("examLogin", loginData).then(() => {
                    this.$router.push({ path:"/exam/start" }).catch(() => {})
                  })
                  .catch((error) => {
                    console.error('登录失败:', error)
                    this.loading = false
                    this.$message.error(error.message || '登录失败')
                  })
            }
          })


    }
  },

  beforeUnmount() {
    // 组件销毁前清除定时器
    if (this.timerId) {
      clearInterval(this.timerId)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.page-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background-color: #1f2d3d;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
  padding: 20px;
}

.header-title {
  width: 100%;
  text-align: center;
  margin-bottom: 30px;
  color: white;

  h1 {
    font-size: 28px;
    font-weight: bold;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    color: #fff;
    margin: 0;
    padding: 15px 0;
    letter-spacing: 2px;
  }
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  flex-direction: column;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
  font-size: 24px;
  font-weight: bold;
}

.login-card {
  background: #ffffff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 550px;
  overflow: hidden;
}

.login-tabs {
  display: flex;
  border-bottom: 1px solid #e6e6e6;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 15px 0;
    cursor: pointer;
    font-size: 16px;
    color: #606266;
    transition: all 0.3s;

    &.active {
      color: #409EFF;
      border-bottom: 2px solid #409EFF;
      font-weight: bold;
    }

    &:hover {
      color: #409EFF;
    }
  }
}

.login-form {
  padding: 25px 25px 5px 25px;

  .el-form-item {
    display: flex;
    align-items: center;

    .el-form-item__label {
      flex: 0 0 auto;
      width: 120px; /* 增加label宽度以适应更长的文本 */
      text-align: right;
      padding-right: 12px;
    }

    .el-form-item__content {
      flex: 1;
      display: flex;
      align-items: center;
    }
  }

  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-code {
  width: 35%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
    width: 100%;
    height: 38px;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
  }
}

.protocol {
  position: relative;
  margin-bottom: 15px;
  display: flex;
  align-items: center;

  .protocol-checkbox {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 1px solid #dcdfe6;
    border-radius: 2px;
    cursor: pointer;
    margin-right: 8px;
    position: relative;

    &.active::after {
      content: "";
      position: absolute;
      left: 4px;
      top: 1px;
      width: 6px;
      height: 10px;
      border: solid #409EFF;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
    }

    &.active {
      border-color: #409EFF;
      background-color: #409EFF;
    }
  }

  .protocol-text {
    font-size: 14px;
    color: #606266;
  }

  .protocol-link {
    color: #409EFF;
    text-decoration: none;
    margin-left: 5px;

    &:hover {
      text-decoration: underline;
    }
  }

  .error-msg {
    position: absolute;
    bottom: -20px;
    left: 0;
    color: #f56c6c;
    font-size: 12px;
    margin: 0;
    display: flex;
    align-items: center;

    .msg-icon {
      display: inline-block;
      width: 14px;
      height: 14px;
      background-color: #f56c6c;
      border-radius: 50%;
      color: white;
      text-align: center;
      line-height: 14px;
      margin-right: 5px;
      font-size: 12px;

      &::before {
        content: "!";
      }
    }
  }
}

.register-links {
  width: 100%;
  text-align: center;
  font-size: 14px;
  color: #606266;
  display: flex;
  flex-wrap: wrap;
  .link-type1 {
    color: #409EFF;
    text-decoration: none;
    font-size: 14px;
    margin: 0; /* 关键修改：移除所有外边距 */
    padding: 0; /* 移除内边距 */

    &:hover {
      text-decoration: underline;
    }
  }

  .link-type {
    color: #409EFF;
    text-decoration: none;
    font-size: 14px;

    &:hover {
      text-decoration: underline;
    }
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.register-code {
  width: 38%;
  float: right;

  .el-button {
    width: 100%;
    padding: 10px 0;
  }
}
.custom-button-group {
  .button-container {
    width: 100%;
    display: flex;
    flex-direction: column;

    .button-wrapper {
      display: flex;
      justify-content: center;
      gap: 15px;
      margin-bottom: 15px;
    }

    .link-wrapper {
      text-align: right;
      padding-top: 10px;
    }
  }

  .action-button {
    width: 40%;
  }
}
</style>
